package com.example.tools;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import com.benchi.ncar.R;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;

/**
 * ViewPager实现的轮播图广告自定义视图，如京东首页的广告轮播图效果； 既支持自动轮播页面也支持手势滑动切换页面
 * 
 * @author hyy
 * 
 */
public class SlideShowView extends FrameLayout {

	// 自动轮播的时间间隔
	private int timeInterval = 5;

	// 自动轮播启用开关
	private boolean isAutoPlay = true;

	// 是否重新切换,如果图片滑到最后一张并且继续向右滑,如果图片是一张并且继续向做滑,判断是否开启继续滑动的功能
	private boolean isOpenReset = true;

	// 自定义轮播图的资源ID
	private ArrayList<Integer> imgIntPhoto;// 本地图片
	private ArrayList<String> imgStringPhoto;// 网络图片

	private ArrayList<Object> imgObjecPhoto;

	// 放轮播图片的ImageView 的list
	private List<ImageView> imageViewsList;
	private Context mContext;
	private ViewGroup mLyPosition;// 存储圆点容器,用来存储标注图片显示位置圆点的容器
	private ViewPager viewPager;
	private boolean isDisplaySign;// 是否显示圆点
	private Handler mActivityHandler;
	public int mImgIndex = -1;
	public final static int VIEWPAGER_MSG = 33;
	public boolean isOriginalImg = false;
	GestureDetector mGestureDetector;
	
	public boolean isOriginalImg() {
		return isOriginalImg;
	}

	public void setOriginalImg(boolean isOriginalImg) {
		this.isOriginalImg = isOriginalImg;
	}

	public void setIsDisplaySign(boolean displaySign) {
		isDisplaySign = displaySign;
	}

	// 当前轮播页
	public static int currentItem = 0;
	// 定时任务
	private ScheduledExecutorService scheduledExecutorService;
	// Handler
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			viewPager.setCurrentItem(VIEWPAGER_MSG);
		}

	};

	public SlideShowView(Context context) {
		this(context, null);
	}

	public SlideShowView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public SlideShowView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mContext = context;
	}

	public ArrayList<Integer> getImgIntPhoto() {
		return imgIntPhoto;
	}

	public void setImgIntPhoto(ArrayList<Integer> imgIntPhoto) {
		this.imgIntPhoto = imgIntPhoto;
	}

	public ArrayList<String> getImgStringPhoto() {
		return imgStringPhoto;
	}

	public void setImgStringPhoto(ArrayList<String> imgStringPhoto) {
		this.imgStringPhoto = imgStringPhoto;
	}

	public int getTimeInterval() {
		return timeInterval;
	}

	public void setTimeInterval(int timeInterval) {
		this.timeInterval = timeInterval;
	}

	public boolean isAutoPlay() {
		return isAutoPlay;
	}

	public void setAutoPlay(boolean isAutoPlay) {
		this.isAutoPlay = isAutoPlay;
	}

	public void setIsOpenReset(boolean isReset) {
		isOpenReset = isReset;
	}

	public void setHandler(Handler handler) {
		mActivityHandler = handler;
	}

	/**
	 * 开始轮播图切换
	 */
	private void startPlay() {
		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1,
				timeInterval, TimeUnit.SECONDS);
	}

	/**
	 * 停止轮播图切换
	 */
	public void stopPlay() {
		scheduledExecutorService.shutdown();
	}

	/**
	 * 初始化相关Data
	 */
	public void initData() {
		imageViewsList = new ArrayList<ImageView>();
		initUI(mContext);
		if (isAutoPlay) {
			startPlay();
		}
		if (mImgIndex > 0) {
			settingPageSelected(mImgIndex);
		}

	}

	/**
	 * 初始化Views等UI
	 */
	private void initUI(Context context) {
		LayoutInflater.from(context).inflate(R.layout.layout_slideshow, this,
				true);
		mLyPosition = (ViewGroup) findViewById(R.id.ly_mark);
		int num = 0;
		imgObjecPhoto = new ArrayList<Object>();
		if (imgIntPhoto != null && imgIntPhoto.size() > 0) {
			imgObjecPhoto.addAll(imgIntPhoto);
		}
		if (imgStringPhoto != null && imgStringPhoto.size() > 0) {
			imgObjecPhoto.addAll(imgStringPhoto);
		}
		if (imgObjecPhoto != null && imgObjecPhoto.size() > 0) {

			for (int i = 0; i < imgObjecPhoto.size(); i++) {
				ImageView view = new ImageView(context);
				// view.setImageResource(imageID);
				settingImg(view, imgObjecPhoto.get(i));
				if (isOriginalImg) {
					view.setScaleType(ScaleType.FIT_CENTER);
				} else {
					view.setScaleType(ScaleType.FIT_XY);
				}
				view.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if (mActivityHandler != null) {
							mActivityHandler.sendEmptyMessage(VIEWPAGER_MSG);
						}

					}
				});
				imageViewsList.add(view);
				LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
						16, 16);
				lp.setMargins(5, 0, 5, 0);
				ImageView viewImage = new ImageView(mContext);
				// viewImage.setId(imageID);
				viewImage.setLayoutParams(lp);
				viewImage.setPadding(50, 0, 50, 0);
				if (num == 0) {
					viewImage.setBackgroundResource(R.drawable.dot_focused);
					num++;
				} else {
					viewImage.setBackgroundResource(R.drawable.dot_normal);
				}
				mLyPosition.addView(viewImage);
			}

			viewPager = (ViewPager) findViewById(R.id.viewPager);
			viewPager.setFocusable(true);

			viewPager.setAdapter(new MyPagerAdapter());
			if (mImgIndex >= 0) {
				viewPager.setCurrentItem(mImgIndex);
			}
			viewPager.setOnPageChangeListener(new MyPageChangeListener());
			if (!isDisplaySign) {
				mLyPosition.setVisibility(View.INVISIBLE);
			}

		}
	}

	/**
	 * 填充ViewPager的页面适配器
	 * 
	 * @author hyy
	 */
	private class MyPagerAdapter extends PagerAdapter {

		@Override
		public void destroyItem(View container, int position, Object object) {
			((ViewPager) container).removeView(imageViewsList.get(position));
		}

		@Override
		public Object instantiateItem(View container, int position) {
			((ViewPager) container).addView(imageViewsList.get(position));
			return imageViewsList.get(position);
		}

		@Override
		public int getCount() {
			return imageViewsList.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}

		@Override
		public void finishUpdate(View arg0) {

		}

	}

	/**
	 * ViewPager的监听器 当ViewPager中页面的状态发生改变时调用
	 * 
	 * @author hyy
	 */
	private class MyPageChangeListener implements OnPageChangeListener {

		boolean isAutoPlay = false;

		@Override
		public void onPageScrollStateChanged(int arg0) {
			switch (arg0) {
			case 1:// 手势滑动，空闲中
				isAutoPlay = false;
				break;
			case 2:// 界面切换中
				isAutoPlay = true;
				break;
			case 0:// 滑动结束，即切换完毕或者加载完毕
				if (isOpenReset) {
					// 当前为最后一张，此时从右向左滑，则切换到第一张
					if (viewPager.getCurrentItem() == viewPager.getAdapter()
							.getCount() - 1 && !isAutoPlay) {
//						viewPager.setCurrentItem(0);
						mActivityHandler.sendEmptyMessage(3);
					}
					// 当前为第一张，此时从左向右滑，则切换到最后一张
					else if (viewPager.getCurrentItem() == 0 && !isAutoPlay) {
//						viewPager.setCurrentItem(viewPager.getAdapter()
//								.getCount() - 1);
					}
				}
				break;
			}
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageSelected(int position) {
			currentItem = position;
			for (int i = 0; i < mLyPosition.getChildCount(); i++) {
				if (i == position) {
					((ImageView) mLyPosition.getChildAt(i))
							.setBackgroundResource(R.drawable.dot_focused);
				} else {
					((ImageView) mLyPosition.getChildAt(i))
							.setBackgroundResource(R.drawable.dot_normal);
				}
			}
		}

	}

	public void settingPageSelected(int position) {
		for (int i = 0; i < mLyPosition.getChildCount(); i++) {
			if (i == position) {
				((ImageView) mLyPosition.getChildAt(i))
						.setBackgroundResource(R.drawable.dot_focused);
			} else {
				((ImageView) mLyPosition.getChildAt(i))
						.setBackgroundResource(R.drawable.dot_normal);
			}
		}
	}

	/**
	 * 执行轮播图切换任务
	 * 
	 * @author hyy
	 */
	private class SlideShowTask implements Runnable {

		@Override
		public void run() {
			synchronized (viewPager) {
				currentItem = (currentItem + 1) % imageViewsList.size();
				handler.obtainMessage().sendToTarget();
			}
		}

	}

	/**
	 * 销毁ImageView资源，回收内存
	 * 
	 * @author hyy
	 */
	public void destoryBitmaps() {

		for (int i = 0; i < imageViewsList.size(); i++) {
			ImageView imageView = imageViewsList.get(i);
			Drawable drawable = imageView.getDrawable();
			if (drawable != null) {
				// 解除drawable对view的引用
				drawable.setCallback(null);
			}
		}
	}

	private void settingImg(ImageView view, Object object) {
		if (object instanceof String) {
			ImageUtils.imgLoader(mContext).displayImage(object.toString(),
					view, ImageUtils.options);
		} else if (object instanceof Integer) {
			view.setImageResource(Integer.valueOf(object.toString()));
		}
	}
}